﻿#include "ZmqSubscriber.h"
#include <iostream>

#include <vector>
#define CLI_CR_RED          "\033[31m"
#define CLI_CR_YELLOW       "\033[33m"
#define CLI_CR_CLOSE        "\033[0m"

ZmqSubscriber::ZmqSubscriber()
{
    m_context = NULL;
    m_socket = NULL;
}

ZmqSubscriber::~ZmqSubscriber()
{
}

int ZmqSubscriber::Connect(const char*  szSvrIp, int port)
{
	char address[64];
	sprintf(address, "tcp://%s:%d", szSvrIp, port);
	return Connect(address);
}

int ZmqSubscriber::Connect(const char *address)
{
    m_context = zmq_ctx_new();
    if (!m_context) {
        std::cerr<<CLI_CR_RED<<"[Subscriber] "<< "Subscriber::failed to create context! with error :"<<zmq_strerror(zmq_errno())<<std::endl<<CLI_CR_CLOSE;
        return -1;
    }

    m_socket = zmq_socket(m_context, ZMQ_SUB);


    if (!m_socket) {
        std::cerr<<CLI_CR_RED<<"[Subscriber] " << "Subscriber::failed to create subscriber socket! with error :"<<zmq_strerror(zmq_errno())<<std::endl<<CLI_CR_CLOSE;
        return -2;
    }

    int ret = zmq_setsockopt(m_socket, ZMQ_SUBSCRIBE, NULL, 0);
    if (ret !=0) {
        std::cerr<<CLI_CR_RED<<"[Subscriber] " << "Subscriber::failed to set subscriber filter! with error :"<<zmq_strerror(zmq_errno())<<std::endl<<CLI_CR_CLOSE;
        return -3;
    }

    ret = zmq_connect(m_socket, address);
    if (ret < 0)
	{
        std::cerr<<CLI_CR_RED<<"[Subscriber] " << "Subscriber::Subscriber socket failed to connect port number :"<<address<<" with return value :"<<ret<<"with error :"<<zmq_strerror(zmq_errno())<<std::endl<<CLI_CR_CLOSE;
        return ret;
    }
	else
	{
		std::cout << "[Subscriber] " << "Subscriber::Connect to server,bind with address :" << address << std::endl;
	}
    return 0;
}

int ZmqSubscriber::resv(char *data, int length){
	char *buf = new char[1024];
	memset(buf,0,1024);
	DWORD gotLen = zmq_recv(m_socket, buf, 1024, 0);
	memcpy(data, buf, 1024);
	length = strlen(data);
	return 0;
}
